package com.data.sessioncounter;

import com.data.Const;
import com.data.josonbean.auth.Auth;
import com.data.service.user.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Created by silenceholic on 2017/5/12.
 */
public class SessionCounter implements HttpSessionListener,ServletContextListener{



    private AuthService authServiceForSession;
    private WebApplicationContext springContext;


    private static final Logger logger = LoggerFactory.getLogger(SessionCounter.class);



    @Override
    public void contextInitialized(ServletContextEvent sce) {
        springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        //执行初始化操作
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    public void sessionCreated(HttpSessionEvent se) {

    }
    public void sessionDestroyed(HttpSessionEvent se) {
//        springContext = WebApplicationContextUtils.getWebApplicationContext();
//        String sessionid = se.getSession().getId();
        Object sysUser = se.getSession().getAttribute(Const.SESSION_USER);
        synchronized (this){
            if (null != sysUser ){
//                System.out.print("session destroy"+sessionid);

                authServiceForSession = (AuthService)springContext.getBean("authService");
                Short i = 0;
                authServiceForSession.updateUserState((Auth)sysUser,i);
                se.getSession().removeAttribute(Const.SESSION_USER);
            }
        }
    }
}
